package com.cqut.servlet;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletvalidCode extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 定义验证码图片的宽度和高度
    private static final int WIDTH = 83;
    private static final int HEIGHT = 30;
    // 定义验证码字符的数量
    private static final int CODE_COUNT = 4;
    // 定义验证码字符的字体
    private static final Font FONT = new Font("Arial", Font.BOLD, 30);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("image/jpeg");
        // 创建验证码图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics g = image.getGraphics();
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        // 生成随机验证码
        String validCode = generateValidCode();
        // 将验证码保存到Session中
        request.getSession().setAttribute("validCode", validCode);
        // 绘制验证码字符
        g.setFont(FONT);
        Random random = new Random();
        for (int i = 0; i < CODE_COUNT; i++) {
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g.drawString(String.valueOf(validCode.charAt(i)), 20 * i + 10, 30);
        }
        // 绘制干扰线
        for (int i = 0; i < 5; i++) {
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }
        // 释放图形上下文
        g.dispose();
        // 输出图像到客户端
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    // 生成随机验证码
    private String generateValidCode() {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < CODE_COUNT; i++) {
            int index = random.nextInt(base.length());
            sb.append(base.charAt(index));
        }
        return sb.toString();
    }
}